<template>
  <div class="min-h-screen">
    <keep-alive>
      <transition name="fade" mode="out-in">
        <component 
          :is="currentComponent"
          v-if="currentPage !== 'menu'"
          ref="currentComponentRef"
          @back="handleBack"
          @showPatterns="handleMenuSelect('patterns')"
          @gotoGame="handleGotoGame"
        />
      </transition>
    </keep-alive>

    <!-- 主菜单 -->
    <transition name="fade" mode="out-in">
      <MainMenu 
        v-if="currentPage === 'menu'" 
        @select="handleMenuSelect" 
      />
    </transition>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick } from 'vue'
import MainMenu from './components/MainMenu.vue'
import GameBoard from './components/GameBoard.vue'
import LoadGame from './components/LoadGame.vue'
import Patterns from './components/Patterns.vue'
import About from './components/About.vue'

const currentPage = ref('menu')
const currentComponentRef = ref(null)
const isTransitioning = ref(false)
const lastPage = ref('menu')

// 组件映射表
const componentMap = {
  game: GameBoard,
  load: LoadGame,
  patterns: Patterns,
  about: About
}

// 计算当前应该显示的组件
const currentComponent = computed(() => {
  return componentMap[currentPage.value]
})

// 处理菜单选择
const handleMenuSelect = async (page) => {
  if (isTransitioning.value) return
  isTransitioning.value = true

  // 如果当前页面是游戏页面，保存游戏状态
  if (currentPage.value === 'game' && currentComponentRef.value?.saveGameState) {
    currentComponentRef.value.saveGameState()
  }

  // 等待过渡动画完成
  await new Promise(resolve => setTimeout(resolve, 300))
  lastPage.value = currentPage.value
  currentPage.value = page
  isTransitioning.value = false
}

// 处理返回操作
const handleBack = async () => {
  if (isTransitioning.value) return
  isTransitioning.value = true

  // 如果当前页面是游戏页面，保存游戏状态
  if (currentPage.value === 'game' && currentComponentRef.value?.stopGame) {
    currentComponentRef.value.stopGame()
    lastPage.value = 'menu'
  }

  // 等待过渡动画完成
  await new Promise(resolve => setTimeout(resolve, 300))
  currentPage.value = lastPage.value
  isTransitioning.value = false
}

// 处理跳转到游戏页面
const handleGotoGame = async () => {
  if (isTransitioning.value) return
  isTransitioning.value = true
  lastPage.value = currentPage.value
  currentPage.value = 'game'
  await nextTick()
  isTransitioning.value = false
}

// 监听页面切换，确保组件状态正确
watch(currentPage, async (newPage) => {
  // 切换到游戏页面时，只在从菜单页面进入时初始化游戏
  if (newPage === 'game') {
    await nextTick()
    if (currentComponentRef.value) {
      if (lastPage.value === 'menu') {
        console.log('App.vue: 从菜单页面进入，初始化游戏组件')
        currentComponentRef.value.initGame()
      } else {
        console.log('App.vue: 从其他页面返回，恢复游戏状态')
        currentComponentRef.value.restoreGameState()
      }
    }
  }
})
</script>

<style>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style> 